from apps.tenant.types import ProviderTelehealthType
from django.conf import settings
import requests
from rest_framework.exceptions import ValidationError


def get_access_token(code):
    headers = {
        'code': code,
        'client_id': settings.GOOGLE_CLIENT_ID,
        'client_secret': settings.GOOGLE_CLIENT_SECRET,
        'redirect_uri': settings.GOOGLE_REDIRECT_URI,
        'grant_type': 'authorization_code'
    }
    response = requests.post(url='https://oauth2.googleapis.com/token', data=headers)
    if response.status_code == 200:
        return response.json()
    else:
        raise ValidationError({"msg": "Your code has been expired"})


def obtain_zoom_tokens(authorization_code):

    # Exchange the authorization code for tokens
    data = {
        'grant_type': 'authorization_code',
        'code': authorization_code,
        'client_id': settings.ZOOM_CLIENT_ID,
        'client_secret': settings.ZOOM_CLIENT_SECRET,
        'redirect_uri': settings.ZOOM_REDIRECT_URI
    }
    response = requests.post('https://zoom.us/oauth/token', data=data)
    if response.status_code == 200:
        return response.json()
    raise ValidationError('Invalid Grant')


def get_telehealth_token(data):
    telehealth_type = data.get('telehealth_type', None)
    if telehealth_type is None:
        raise ValidationError({'You must provide a telehealth type'})
    else:
        if telehealth_type == str(ProviderTelehealthType.GOOGLE_MEET.value):
            code = data.get('code', None)
            if code:
                response = get_access_token(code)
                return response['access_token'], response['refresh_token']
            else:
                raise ValidationError('Code must be provided')
        elif telehealth_type == str(ProviderTelehealthType.ZOOM.value):
            code = data.get('code', None)
            if code:
                response = obtain_zoom_tokens(code)

                return response['access_token'], response['refresh_token']
            else:
                raise ValidationError('Code must be provided')